﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using bzxxxt.admin.entity;
using bzxxxt.admin.service;
using bzxxxt.dal;
using System.Text.RegularExpressions;

namespace bzxxxt.admin.ashx
{
    /// <summary>
    /// rm_user 的摘要说明
    /// </summary>
    public class rm_user : rm_base
    {
        UserService s = new UserService();
        public override void getall(HttpContext context)
        {
            string json = s.getall();
            context.Response.Write(json);
        }

        public override void search(HttpContext context)
        {
            string strWhere = context.Request.Params["where"] ?? "1=1";
            string sort = context.Request.Params["sort"] ?? "id";   //排序列
            string order = context.Request.Params["order"] ?? "asc";     //排序方式 asc或者desc
            int pageIndex = int.Parse(context.Request.Params["page"] ?? "1");
            int pageSize = int.Parse(context.Request.Params["rows"] ?? "20");

            string json = s.search(pageSize, pageIndex, sort + " " + order, strWhere);
            context.Response.Write(json);

        }

        public override void add(HttpContext context)
        {
            string username = context.Request.Params["ui_user_username_edit"] ?? "";
            string userpwd = context.Request.Params["ui_user_userpwd_edit"] ?? "";           
            string realname = context.Request.Params["ui_user_realname_edit"] ?? "";
            string tel = context.Request.Params["ui_user_tel_edit"] ?? "";
            string status = context.Request.Params["ui_user_status_edit"] ?? "";
            string strPoints = context.Request.Params["ui_user_points_edit"];
            if (string.IsNullOrEmpty(strPoints)) strPoints = "0";
            int points = Convert.ToInt32(strPoints);
            string desc = context.Request.Params["ui_user_description_edit"] ?? "";

            var pwdRegex = new Regex("(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}");
            Match m = pwdRegex.Match(userpwd);
            if (!m.Success)
            {
                context.Response.Write(JsonUtil.ToJson(new
                {
                    success = false,
                    msg = "密码中必须包含大小写字母、数字、特殊字符，至少8位！"
                }));
                return;
            }
            tbUser b = new tbUser
            {                
                userName = username,
                userPwd = userpwd,
                realName = realname,
                able = string.IsNullOrEmpty(status) ? false : true,
                tel = tel,
                points = points,
                description = desc,
                addDate = DateTime.Now
            };
            string json = s.add(b);
            context.Response.Write(json);

        }
        public override void edit(HttpContext context)
        {
            int id = Convert.ToInt32(context.Request.Params["ui_user_id_edit"] ?? "0");
            string username = context.Request.Params["ui_user_username_edit"] ?? "";
            string userpwd = context.Request.Params["ui_user_userpwd_edit"] ?? "";
            string realname = context.Request.Params["ui_user_realname_edit"] ?? "";
            string tel = context.Request.Params["ui_user_tel_edit"] ?? "";
            string status = context.Request.Params["ui_user_status_edit"] ?? "";
            string strPoints = context.Request.Params["ui_user_points_edit"];
            if (string.IsNullOrEmpty(strPoints)) strPoints = "0";
            int points = Convert.ToInt32(strPoints);
            string desc = context.Request.Params["ui_user_description_edit"] ?? "";

            var pwdRegex = new Regex("(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}");
            Match m = pwdRegex.Match(userpwd);
            if (!m.Success)
            {
                context.Response.Write(JsonUtil.ToJson(new
                {
                    success = false,
                    msg = "密码中必须包含大小写字母、数字、特殊字符，至少8位！"
                }));
                return;
            }

            tbUser b = new tbUser
            {
                id = id,
                userName = username,
                userPwd = userpwd,
                realName = realname,
                able = string.IsNullOrEmpty(status) ? false : true,
                tel = tel,
                points = points,
                description = desc,
                addDate = DateTime.Now
            };
            string json = s.edit(b);
            context.Response.Write(json);
        }

        public override void delete(HttpContext context)
        {
            string ids = context.Request.Params["ids"];
            string json = s.delete(ids);
            context.Response.Write(json);
        }

        public override void other(HttpContext context)
        {
            string action = context.Request.Params["action"];
            UserEntity userFromCookie = UserService.GetUser(context);   //获取cookie里的用户对象
            switch (action) {
                case "setdept":
                    {
                        string userIds = context.Request.Params["ui_user_setdept_userid"] ?? "";
                        string deptIds = context.Request.Params["ui_user_setdept_dept"] ?? "";
                        string json = s.setdetp(userIds, deptIds);
                        context.Response.Write(json);
                        break;
                    }
                case "setrole":
                    {
                        string userIds = context.Request.Params["ui_user_setrole_userid"] ?? "";  //用户id，可能是多个
                        string roleIds = context.Request.Params["ui_user_setrole_role"] ?? "";  //角色id，可能是多个
                        string json = s.setrole(userIds, roleIds);
                        context.Response.Write(json);
                        break;
                    }
                case "getUserInfo": 
                    {                        
                        context.Response.Write(JsonUtil.ToJson(userFromCookie));
                        break;
                    }
                case "changepwd":
                    {
                        string oldPwd = context.Request.Params["ui_user_changepwd_originalpwd"] ?? "";
                        string newPwd = context.Request.Params["ui_user_changepwd_newpwd"] ?? "";
                        var pwdRegex = new Regex("(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}");
                        Match m = pwdRegex.Match(newPwd);
                        if (!m.Success)
                        {
                            context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "密码中必须包含大小写字母、数字、特殊字符，至少8位！" }));
                            break;
                        }
                        oldPwd = Md5.GetMD5String(oldPwd);
                        if (oldPwd != userFromCookie.userPwd)
                        {
                            context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "原密码不正确！" }));
                        }
                        else
                        {
                            newPwd = Md5.GetMD5String(newPwd);
                            string json = s.changepwd(userFromCookie.id, newPwd);
                            FormsAuthentication.SignOut();
                            context.Response.Write(json);
                        }
                        
                        break;
                    }
                case "import":
                    {
                        string op = context.Request.Params["op"];
                        if (op == "upload")
                        {
                            UserEntity user = UserService.GetUser(context);
                            //文件名  
                            HttpPostedFile f1 = context.Request.Files["ui_user_import_file"];

                            string fileExt = System.IO.Path.GetExtension(f1.FileName);
                            if (!(fileExt == ".xls" || fileExt == ".xlsx"))
                            {
                                context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "只支持扩展名为.xls或.xlsx文件！" }));
                                return;
                            }
                            string fileName = user.userName + "_user_" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
                            f1.SaveAs(context.Server.MapPath("~/admin/upload/") + fileName);
                            context.Response.Write(JsonUtil.ToJson(new { success = true, msg = fileName }));
                        }
                        else if (op == "import")
                        {
                            string file = context.Request.Params["ui_user_import_filename"];

                            if (string.IsNullOrEmpty(file))
                            {
                                context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "文件未上传！" }));
                            }
                            else
                            {
                                file = context.Server.MapPath("~/admin/upload/") + file;
                                try
                                {
                                    List<UserEntity> list = s.ImportExceltoDb(file, 0, 0);
                                    s.Import(list);
                                    context.Response.Write(JsonUtil.ToJson(new { success = true, msg = "导入成功！" }));
                                }
                                catch (Exception ex)
                                {

                                    context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "导入失败: " + ex.Message }));
                                }
                            }
                        }
                        break;
                    }
            }
        }
    }
}